
import * as cheerio from 'react-native-cheerio';
import { ISearchResult } from "../def";
import { SupportVideoType, VideoIntroduceInfo, VideoDetailInfo, VideoItem, PlaySource, Episode } from "../icommon/index";

async function search<T extends SupportVideoType>(query: string, page: number, type: T): Promise<ISearchResult<T>> {
    const movies: VideoItem[] = [];
    let url = "https://www.xb6v.com";

    // 根据类型和页码构建URL
    if (query) {
        url = `https://www.xb6v.com/search.php?searchword=${encodeURIComponent(query)}&page=${page}`;
    } else {
        // 根据类型选择不同的页面
        switch (type) {
            case "movies":
                if (page <= 1) {
                    url = "https://www.xb6v.com/xijupian/";
                    break;
                }
                url = `https://www.xb6v.com/xijupian/index_${page}.html`;
                break;
            case "tv":
                if (page <= 1) {
                    url = "https://www.xb6v.com/dianshiju/";
                    break;
                }
                url = `https://www.xb6v.com/dianshiju/index_${page}.html`;
                break;
            case "cartoon":
                if (page <= 1) {
                    url = "https://www.xb6v.com/donghuapian/";
                    break;
                }
                url = `https://www.xb6v.com/donghuapian/index_${page}.html`;
                break;
            default:
                url = `https://www.xb6v.com/index_${page}.html`;
        }
    }

    const res = await fetch(url, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);

    // 解析搜索结果列表
    $('#post_container li').each((index: number, element: any) => {
        const linkElement = $(element).find('.zoom');
        const titleElement = $(element).find('h2 a');
        const imgElement = $(element).find('.thumbnail img');

        if (linkElement.length > 0 && titleElement.length > 0) {
            const detailUrl = linkElement.attr('href') || '';
            const title = titleElement.text() || '';
            const cover = imgElement.attr('src') || '';

            // 从详情地址中提取ID
            const idMatch = detailUrl.match(/\/(\d+)\.html/);
            const id = idMatch ? idMatch[1] : '';

            if (id && title && detailUrl) {
                movies.push({
                    id,
                    title,
                    img: cover,
                    detailUrl
                });
            }
        }
    });

    return {
        data: movies,
        isEnd: movies.length <= 0,
    };
}
async function fetchIntroduceInfo({ id, url }: { url: string, id: string }): Promise<VideoIntroduceInfo> {
    const target = `https://www.xb6v.com/${url}`;
    const res = await fetch(target, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);

    // 提取基本信息
    const title = $('h1').text().trim() || $('.article_container h1').text().trim();
    const cover = $('.thumbnail img').attr('src') || $('#post_content img').first().attr('src') || '';

    // 提取各种字段信息
    const description = $('meta[name="description"]').attr('content') || '';

    // 从页面内容中提取详细信息
    let director = '';
    let actor = '';
    let category = '';
    let area = '';
    let year = '';
    let updateTime = '';

    // 在页面中查找影片信息
    $('#post_content p').each((i: number, el: any) => {
        const text = $(el).text();
        if (text.includes('导　　演')) {
            director = text.replace('◎导　　演', '').trim();
        } else if (text.includes('主　　演')) {
            actor = text.replace('◎主　　演', '').trim();
        } else if (text.includes('类　　别')) {
            category = text.replace('◎类　　别', '').trim();
        } else if (text.includes('产　　地')) {
            area = text.replace('◎产　　地', '').trim();
        } else if (text.includes('年　　代')) {
            year = text.replace('◎年　　代', '').trim();
        }
    });

    // 提取播放地址
    const playUrls: string[] = [];
    $('.widget a.lBtn').each((index: number, element: any) => {
        const playUrl = $(element).attr('href');
        if (playUrl) {
            playUrls.push(playUrl);
        }
    });

    const playUrl = playUrls.length > 0 ? playUrls[0] : '';

    return {
        id,
        title,
        img: cover,
        introduce: description,
        actor,
        director,
        category,
        area,
        year,
        updateTime,
        detailUrl: playUrl,
    } as VideoIntroduceInfo;
}
async function fetchVideoDetailInfo({ id, url, source, episodeIndex }: {
    url: string
    id: string,
    source?: number,
    episodeIndex?: number
}): Promise<VideoDetailInfo> {
    // 构建播放页面URL
    const target = `https://www.xb6v.com/${url}`;
    const res = await fetch(target, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    });
    const html = await res.text();
    const $ = cheerio.load(html);

    const title = $('title').text().split('-')[0].trim() || '视频播放';
    const description = $('meta[name="description"]').attr('content') || '';

    // 提取播放源信息
    const playSources: PlaySource[] = [];
    $('.widget h3').each((index: number, element: any) => {
        const sourceName = $(element).text().trim();
        if (sourceName.includes('播放地址')) {
            playSources.push({
                id: `source_${index}`,
                name: sourceName,
                episodes: []
            });
        }
    });

    // 提取各播放源的选集
    $('.widget a.lBtn').each((index: number, element: any) => {
        const episodeTitle = $(element).text().trim() || `播放地址${index + 1}`;
        const episodeUrl = $(element).attr('href') || '';

        if (playSources.length > 0) {
            playSources[0].episodes.push({
                id: id,
                sourceIndex: source || 0,
                episodeIndex: index,
                title: episodeTitle,
                url: episodeUrl
            });
        }
    });

    // 获取当前播放的视频信息
    let videoUrl = '';
    $('.video iframe').each((index: number, element: any) => {
        const src = $(element).attr('src');
        if (src) {
            videoUrl = src;
        }
    });

    const match = videoUrl.match(/^(https?):\/\/([^\/\?#]+)/); 
    const pre = `${match![1]}://${match![2]}`
    console.log("parse video url", videoUrl, pre);
    const videoUrlHtml = await fetch(videoUrl, {
        headers: {
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1",
        },
    }).then(res => res.text());

    const $2 = await cheerio.load(videoUrlHtml);
    // 从script标签中提取url变量
    $2('script').each((index: number, element: any) => {
        const scriptContent = $(element).html() || '';
        // 查找包含url变量定义的脚本
        const urlMatch = scriptContent.match(/const\s+url\s*=\s*["'](.*?\.m3u8.*?)["']/);
        if (urlMatch && urlMatch[1]) {
            // 如果是相对路径，需要补全
            if (urlMatch[1].startsWith('/')) {
                videoUrl = `${pre}${urlMatch[1]}`;
            } else {
                videoUrl = urlMatch[1];
            }
        }
    });

    const currentVideoInfo = {
        id: id,
        videoUrl: videoUrl,
        currentEpisode: 0,
        currentSource: "0",
    };

    return {
        id,
        title,
        img: '',
        introduce: description,
        playSources,
        currentVideoInfo,
        detailUrl: url,
    } as VideoDetailInfo;
}
module.exports = {
    label: "6V电影",
    platform: "sixvdy",
    srcUrl: "https://www.xb6v.com",
    author: "petter.he",
    description: "6V电影网站插件",
    enabledSearch: true,
    search,
    fetchIntroduceInfo,
    fetchVideoDetailInfo,
}
